from flask import Flask, request, jsonify
import psutil
import wmi
import platform
from datetime import datetime

app = Flask(__name__)

@app.route('/api/system_info', methods=['POST'])
def system_info():
    try:
        # 获取系统信息
        sys_info = {
            'platform': platform.system(),
            'platform-release': platform.release(),
            'platform-version': platform.version(),
            'architecture': platform.machine(),
            'hostname': platform.node(),
            'processor': platform.processor(),
            'ram': str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB",
            '逻辑处理器个数': psutil.cpu_count(logical=True),
            '处理器核心数': psutil.cpu_count(logical=False),
            'CPU使用率': psutil.cpu_percent(interval=1),
            '磁盘情况': get_disk_info,
            'disk_usage': psutil.disk_usage('/').percent,
            'boot_time': datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"),
            'network': [{'interface': iface, 'addresses': addrs} for iface, addrs in psutil.net_if_addrs().items()]
        }

        return jsonify(sys_info), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 仅获取CPU相关信息
@app.route('/api/system_cpu', methods=['POST'])
def system_cpu():
    try:
        cpu_info = {
            '逻辑处理器个数': psutil.cpu_count(logical=True),
            '处理器核心数': psutil.cpu_count(logical=False),
            'CPU使用率': psutil.cpu_percent(interval=1)
        }
        return jsonify(cpu_info), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 获取所有挂载的磁盘分区信息及每个分区的磁盘使用情况
@app.route('/api/disk_info', methods=['GET'])
def get_disk_info():
    try:
        # 获取磁盘分区信息（仅物理设备）
        partitions = psutil.disk_partitions(all=False)
        
        # 构建响应字典，并添加中文标注
        response = []
        for partition in partitions:
            try:
                # 获取指定路径的磁盘使用情况
                usage = psutil.disk_usage(partition.mountpoint)
                
                partition_info = {
                    '设备': partition.device,
                    '挂载点': partition.mountpoint,
                    '文件系统类型': partition.fstype,
                    '挂载选项': partition.opts,
                    '总空间 (字节)': usage.total,
                    '已用空间 (字节)': usage.used,
                    '可用空间 (字节)': usage.free,
                    '使用率 (%)': usage.percent
                }
                response.append(partition_info)
            except FileNotFoundError:
                partition_info = {
                    '设备': partition.device,
                    '挂载点': partition.mountpoint,
                    '文件系统类型': partition.fstype,
                    '挂载选项': partition.opts,
                    '错误': f'路径 {partition.mountpoint} 不存在'
                }
                response.append(partition_info)
            except Exception as e:
                partition_info = {
                    '设备': partition.device,
                    '挂载点': partition.mountpoint,
                    '文件系统类型': partition.fstype,
                    '挂载选项': partition.opts,
                    '错误': str(e)
                }
                response.append(partition_info)

        return jsonify(response), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 获取所有挂载的磁盘分区信息及每个分区的磁盘使用情况
@app.route('/api/info', methods=['GET'])
def get_hardware_info():
    try:
        WMI = wmi.WMI()        
        hardware_info = {}

        # 硬盘信息
        disks = []
        for diskinfo in WMI.Win32_DiskDrive():
            if '虚拟' not in diskinfo.Caption:
                disks.append({
                    '制造商': diskinfo.Manufacturer,
                    '序列号': diskinfo.SerialNumber,
                    '硬盘大小': diskinfo.Size
                })
        hardware_info['disks'] = disks

        # CPU信息
        cpus = []
        for cpuinfo in WMI.Win32_Processor():
            cpus.append({
                '名称': cpuinfo.Name,
                '制造商': cpuinfo.Manufacturer,
                'ID号': cpuinfo.ProcessorId,
                '序列号': cpuinfo.SerialNumber,
                '核心数': cpuinfo.NumberOfCores
            })
        hardware_info['cpus'] = cpus

        # 主板信息
        boards = []
        for boardinfo in WMI.Win32_BaseBoard():
            boards.append({
                '制造商': boardinfo.Manufacturer,
                '产品号': boardinfo.Product,
                '序列号': boardinfo.SerialNumber
            })
        hardware_info['boards'] = boards

        # 网卡信息
        network_adapters = []
        for NetworkAdapter in WMI.Win32_NetworkAdapter():
            if NetworkAdapter.MACAddress:
                network_adapters.append({
                    '名称': NetworkAdapter.Name,
                    '制造商': NetworkAdapter.Manufacturer,
                    'MAC地址': NetworkAdapter.MACAddress
                })
        hardware_info['network_adapters'] = network_adapters

        # BIOS信息
        bioses = []
        for biosinfo in WMI.Win32_BIOS():
            bioses.append({
                '名称': biosinfo.Name,
                '制造商': biosinfo.Manufacturer,
                '序列号': biosinfo.SerialNumber
            })
        hardware_info['bioses'] = bioses

        # 内存信息
        memories = []
        for memoryinfo in WMI.Win32_PhysicalMemory():
            memories.append({
                '制造商': memoryinfo.Manufacturer,
                '部件号': memoryinfo.PartNumber,
                '序列号': memoryinfo.SerialNumber,
                '内存大小': memoryinfo.Capacity
            })
        hardware_info['memories'] = memories

        return jsonify(hardware_info), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(port=11223,debug=True)